<template>
	<el-dialog v-model="visible" title="已完成分段的未完成项管理" width="95%" :close-on-click-modal="false" @close="handleClose">
		<div class="incomplete-items-container">
			<!-- 查询区域 -->
			<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
				<el-form :model="queryParams" ref="queryFormRef" label-width="80px" :inline="true">
					<el-form-item label="船号">
						<el-input v-model="queryParams.ch" placeholder="请输入船号" clearable style="width: 150px" />
					</el-form-item>
					<el-form-item label="分段">
						<el-input v-model="queryParams.fd" placeholder="请输入分段" clearable style="width: 150px" />
					</el-form-item>
					<el-form-item label="工作月份">
						<el-date-picker v-model="queryParams.workTime" type="month" value-format="YYYY-MM" placeholder="请选择工作月份" clearable style="width: 150px" />
					</el-form-item>
					<el-form-item label="关键字">
						<el-input v-model="queryParams.keyword" placeholder="请输入关键字" clearable style="width: 150px" />
					</el-form-item>
					<el-form-item>
						<el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
						<el-button icon="Refresh" @click="resetQuery">重置</el-button>
						<el-button type="success" icon="Check" :disabled="!hasSelectedItems || !hasValidUpdates" @click="batchUpdate"> 批量保存 </el-button>
					</el-form-item>
				</el-form>
			</el-card>

			<!-- 数据表格 -->
			<el-card class="full-table" shadow="hover" style="margin-top: 10px">
				<el-table ref="tableRef" :data="tableData" v-loading="tableLoading" style="width: 100%" border row-key="id" @selection-change="handleSelectionChange">
					<el-table-column type="selection" width="50" align="center" fixed="left" />
					<el-table-column type="index" label="序号" width="60" align="center" fixed="left" />
					<el-table-column prop="ch" label="船号" width="100" align="center" fixed="left" show-overflow-tooltip />
					<el-table-column prop="fd" label="分段" width="100" align="center" fixed="left" show-overflow-tooltip />
					<el-table-column prop="classNameFkDisplayName" label="分类" width="120" align="center" show-overflow-tooltip />
					<el-table-column prop="team" label="劳务队" width="100" align="center" show-overflow-tooltip />

					<!-- 分段报验完工日期 -->
					<el-table-column prop="finishDate" label="分段报验完工" width="120" align="center" show-overflow-tooltip>
						<template #default="scope">
							<el-tag type="success" size="small">{{ formatDate(scope.row.finishDate) }}</el-tag>
						</template>
					</el-table-column>

					<!-- 计划时间 -->
					<el-table-column label="计划时间" width="240" align="center">
						<el-table-column prop="planStart" label="计划开工" width="120" align="center" show-overflow-tooltip>
							<template #default="scope">
								{{ formatDate(scope.row.planStart) }}
							</template>
						</el-table-column>
						<el-table-column prop="planEnd" label="计划完工" width="120" align="center" show-overflow-tooltip>
							<template #default="scope">
								{{ formatDate(scope.row.planEnd) }}
							</template>
						</el-table-column>
					</el-table-column>

					<!-- 实际时间（可编辑） -->
					<el-table-column label="实际时间" width="300" align="center">
						<el-table-column label="实际开工" width="150" align="center">
							<template #default="scope">
								<el-date-picker
									v-model="scope.row.editActualStart"
									type="datetime"
									value-format="YYYY-MM-DD"
									format="YYYY-MM-DD"
									placeholder="实际开工时间"
									size="small"
									style="width: 140px"
									:class="{ 'missing-field': scope.row.missingActualStart }"
									@change="handleTimeChange(scope.row)"
								/>
							</template>
						</el-table-column>
						<el-table-column label="实际完工" width="150" align="center">
							<template #default="scope">
								<el-date-picker
									v-model="scope.row.editActualEnd"
									type="datetime"
									value-format="YYYY-MM-DD"
									format="YYYY-MM-DD"
									placeholder="实际完工日期"
									size="small"
									style="width: 140px"
									:class="{ 'missing-field': scope.row.missingActualEnd }"
									@change="handleTimeChange(scope.row)"
								/>
							</template>
						</el-table-column>
					</el-table-column>

					<!-- 缺失标识 -->
					<el-table-column label="缺失项" width="120" align="center">
						<template #default="scope">
							<div style="display: flex; flex-direction: column; gap: 2px">
								<el-tag v-if="scope.row.missingActualStart" type="danger" size="small">缺开工</el-tag>
								<el-tag v-if="scope.row.missingActualEnd" type="warning" size="small">缺完工</el-tag>
							</div>
						</template>
					</el-table-column>

					<!-- 备注（可编辑） -->
					<el-table-column prop="remark" label="备注" width="200" align="center">
						<template #default="scope">
							<el-input v-model="scope.row.editRemark" type="textarea" :rows="2" placeholder="请输入备注" size="small" @input="handleTimeChange(scope.row)" />
						</template>
					</el-table-column>

					<!-- 操作 -->
					<el-table-column label="操作" width="100" align="center" fixed="right">
						<template #default="scope">
							<el-button type="primary" size="small" :disabled="!scope.row.hasChanges" @click="updateSingle(scope.row)"> 保存 </el-button>
						</template>
					</el-table-column>
				</el-table>

				<!-- 分页 -->
				<div class="table-pagination" style="margin-top: 10px; text-align: right">
					<el-pagination
						v-model:current-page="queryParams.page"
						v-model:page-size="queryParams.pageSize"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						layout="total, sizes, prev, pager, next, jumper"
						:page-sizes="[10, 20, 50, 100]"
						:total="total"
						size="small"
						background
					/>
				</div>
			</el-card>
		</div>
	</el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { usePlanIncompleteItemsApi, PlanIncompleteItemsApi } from '/@/api/plans/incompleteItems';

const incompleteItemsApi = usePlanIncompleteItemsApi();

// 组件状态
const visible = ref(false);
const tableLoading = ref(false);
const queryFormRef = ref();
const tableRef = ref();

// 查询参数
const queryParams = reactive({
	page: 1,
	pageSize: 20,
	ch: '',
	fd: '',
	workTime: '',
	keyword: '',
});

// 数据状态
const tableData = ref<any[]>([]);
const total = ref(0);
const selectedItems = ref<any[]>([]);

// 打开对话框
const openDialog = (presetParams?: any) => {
	visible.value = true;

	// 设置默认月份为当前月份
	const now = new Date();
	queryParams.workTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;

	// 如果有预设参数，应用它们
	if (presetParams) {
		Object.assign(queryParams, presetParams);
	}

	nextTick(() => {
		handleQuery();
	});
};

// 关闭对话框
const handleClose = () => {
	resetQuery();
	selectedItems.value = [];
	tableData.value = [];
};

// 查询数据
const handleQuery = async () => {
	try {
		tableLoading.value = true;
		const response = await incompleteItemsApi.getFinishedSegmentIncompleteItems(queryParams);
		const result = response.data.result;

		// 为每行添加编辑字段和变更标识
		tableData.value = (result?.items || []).map((item: any) => ({
			...item,
			editActualStart: item.actualStart || '',
			editActualEnd: item.actualEnd || '',
			editRemark: item.remark || '',
			hasChanges: false,
		}));

		total.value = result?.total || 0;
	} catch (error) {
		console.error('查询未完成项失败:', error);
		ElMessage.error('查询失败');
	} finally {
		tableLoading.value = false;
	}
};

// 重置查询
const resetQuery = () => {
	queryParams.page = 1;
	queryParams.pageSize = 20;
	queryParams.ch = '';
	queryParams.fd = '';
	queryParams.workTime = '';
	queryParams.keyword = '';
	handleQuery();
};

// 处理分页大小变更
const handleSizeChange = (newSize: number) => {
	queryParams.pageSize = newSize;
	queryParams.page = 1;
	handleQuery();
};

// 处理页面变更
const handleCurrentChange = (newPage: number) => {
	queryParams.page = newPage;
	handleQuery();
};

// 处理选择变更
const handleSelectionChange = (selection: any[]) => {
	selectedItems.value = selection;
};

// 处理时间或备注变更
const handleTimeChange = (row: any) => {
	// 检查是否有变更
	const hasStartChange = row.editActualStart !== (row.actualStart || '');
	const hasEndChange = row.editActualEnd !== (row.actualEnd || '');
	const hasRemarkChange = row.editRemark !== (row.remark || '');

	row.hasChanges = hasStartChange || hasEndChange || hasRemarkChange;
};

// 计算属性：是否有选中项
const hasSelectedItems = computed(() => selectedItems.value.length > 0);

// 计算属性：选中项是否有有效更新
const hasValidUpdates = computed(() => {
	return selectedItems.value.some((item) => item.hasChanges);
});

// 单项更新
const updateSingle = async (row: any) => {
	if (!row.hasChanges) {
		ElMessage.warning('没有需要保存的变更');
		return;
	}

	try {
		const updateItem: PlanIncompleteItemsApi.BatchUpdateItemInput = {
			id: row.id,
			actualStart: row.editActualStart || undefined,
			actualEnd: row.editActualEnd || undefined,
			remark: row.editRemark || undefined,
		};

		const response = await incompleteItemsApi.batchUpdateIncompleteItems([updateItem]);
		const result = response.data.result;

		if (result.successCount > 0) {
			ElMessage.success('保存成功');
			// 更新原始数据
			row.actualStart = row.editActualStart;
			row.actualEnd = row.editActualEnd;
			row.remark = row.editRemark;
			row.hasChanges = false;
		} else {
			ElMessage.error(`保存失败: ${result.errors.join(', ')}`);
		}
	} catch (error) {
		console.error('保存失败:', error);
		ElMessage.error('保存失败');
	}
};

// 批量更新
const batchUpdate = async () => {
	const changedItems = selectedItems.value.filter((item) => item.hasChanges);
	if (changedItems.length === 0) {
		ElMessage.warning('没有需要保存的变更');
		return;
	}

	try {
		await ElMessageBox.confirm(`确定要批量保存${changedItems.length}项变更吗？`, '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		});

		const updateItems: PlanIncompleteItemsApi.BatchUpdateItemInput[] = changedItems.map((item) => ({
			id: item.id,
			actualStart: item.editActualStart || undefined,
			actualEnd: item.editActualEnd || undefined,
			remark: item.editRemark || undefined,
		}));

		const response = await incompleteItemsApi.batchUpdateIncompleteItems(updateItems);
		const result = response.data.result;

		if (result.successCount > 0) {
			ElMessage.success(`成功保存${result.successCount}项变更`);

			// 更新原始数据
			changedItems.forEach((item) => {
				item.actualStart = item.editActualStart;
				item.actualEnd = item.editActualEnd;
				item.remark = item.editRemark;
				item.hasChanges = false;
			});

			// 清除选择
			tableRef.value?.clearSelection();
		}

		if (result.failedCount > 0) {
			ElMessage.warning(`${result.failedCount}项保存失败: ${result.errors.join(', ')}`);
		}
	} catch (error) {
		if (error !== 'cancel') {
			console.error('批量保存失败:', error);
			ElMessage.error('批量保存失败');
		}
	}
};

// 格式化日期
const formatDate = (dateStr: string | null) => {
	if (!dateStr) return '-';
	return dateStr.slice(0, 10);
};

// 暴露方法
defineExpose({
	openDialog,
});
</script>

<style scoped>
.incomplete-items-container {
	height: calc(80vh - 120px);
	overflow: hidden;
}

.full-table {
	height: calc(100% - 80px);
}

:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}

/* 缺失字段高亮样式 */
:deep(.missing-field .el-input__wrapper) {
	border-color: #f56c6c;
	background-color: #fef0f0;
}

:deep(.missing-field .el-input__wrapper:hover) {
	border-color: #f56c6c;
}

/* 表格行高度调整 */
:deep(.el-table .el-table__row) {
	height: 60px;
}

:deep(.el-table .el-table__cell) {
	padding: 4px 0;
}
</style>
